#include "thread.h"

void *threadBase::threadFun(void *arg){
    threadBase *p = (threadBase *)arg;
    while(!p->threadIsExit()){
       if(!p->threadLoop()){
            p->threadExit();
            break;
       }
 
       if(p->threadIsStop()){
            p->waitCond();
       }
    }
    p->threadEnd();
    return p;
}


void threadBase::run(){
    // printf("run in\n");
    readyToRun();
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    state = THREAD_RUNNING;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,	PTHREAD_CREATE_DETACHED);
    pthread_create(&tid, &attr, threadFun, this);
    pthread_detach(tid); 
    // printf("run out\n");
}
 
void threadBase::threadExit(){
    state = THREAD_EXIT;
    printf("threadExit \n");
}
 
bool threadBase::threadIsExit(){
    if(state == THREAD_EXIT){
        return true;
    }
    return false;
}
 
bool threadBase::threadIsStop(){
    if(state == THREAD_STOP){
        return true;
    }
    return false;
}
 
void threadBase::threadStop(){
    printf("threadStop \n");
    if(state == THREAD_RUNNING){
        state = THREAD_STOP;
    }
}
 
void threadBase::threadRerun(){
    if(state == THREAD_STOP){
        state = THREAD_RUNNING;
        sendCond();
    }
}
 
 
 
void threadBase::readyToRun(){
    printf("readyToRun\n");
}
 
void threadBase::readyToEnd(){
    printf("readyToEnd\n");
}
 
void threadBase::threadEnd(){
    readyToEnd();
    pthread_mutex_destroy(&mutex);	//销毁
    pthread_cond_destroy(&cond);	//销毁
    pthread_attr_destroy(&attr);
    printf("threadEnd out\n");
}
 
void threadBase::sendCond(){
    printf("sendCond in\n");
    pthread_cond_signal(&cond);//向条件变量发送信号
    printf("sendCond out\n");
}
 
void threadBase::waitCond(){
    printf("waitCond in\n");
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);
    pthread_mutex_unlock(&mutex);
    printf("waitCond out\n");
}